package com.hainingtong.core.service.impl;

import com.hainingtong.core.dao.AuthMapper;
import com.hainingtong.core.dao.UserMapper;
import com.hainingtong.core.entity.SysAuth;
import com.hainingtong.core.entity.SysUser;
import com.hainingtong.core.exception.NicknameExistsException;
import com.hainingtong.core.exception.PrincipalExistsException;
import com.hainingtong.core.service.UserService;
import com.hainingtong.core.shiro.token.LoginType;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import springfox.documentation.annotations.Cacheable;

import java.util.Objects;


@Transactional // 注解默认只能拦截RuntimeException和Error，如果自定义的Exception，需要如下设置
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Autowired
    AuthMapper authMapper;

    @Override
    public SysUser findUserById(int userId) {
        return userMapper.findById(userId);
    }

    @Override
    public SysUser register(String nickname, String principal, String credential, String loginType) throws Exception {

        try {
            SysUser user = new SysUser();
            user.setNickname(nickname);

            userMapper.insert(user);

            SysAuth auth = new SysAuth();
            auth.setUserId(user.getId());
            auth.setPrincipal(principal);

            credential = BCrypt.hashpw(credential, BCrypt.gensalt());
            auth.setCredential(credential);

            auth.setLoginType(LoginType.valueOf(loginType));

            authMapper.insert(auth);
            return user;
        } catch (DuplicateKeyException e) {
            if (Objects.requireNonNull(e.getMessage()).contains("nickname")) {
                throw new NicknameExistsException();
            } else if (e.getMessage().contains("principal_login_type_unique_index")) {
                throw new PrincipalExistsException();
            }
            throw e;
        }
    }

    @Override
    public SysAuth findAuthByPrincipalAndType(String principal, String type) {
        return authMapper.findByPrincipalAndType(principal, type);
    }

    @Override
    public SysUser findUserByPrincipalAndType(String principal, String type) {
        SysAuth auth = this.findAuthByPrincipalAndType(principal, type);
        if (auth == null) {
            return null;
        }
        return userMapper.findById(auth.getUserId());
    }
}
